<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel Question Import Tool</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 30px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: #2c5aa0;
        }
        .upload-area {
            border: 2px dashed #2c5aa0;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            background-color: #f0f4f8;
        }
        .upload-area.dragover {
            background-color: #e3f2fd;
            border-color: #1976d2;
        }
        .file-input {
            display: none;
        }
        .btn {
            background: linear-gradient(135deg, #2c5aa0 0%, #1e3a8a 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px;
        }
        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .preview-area {
            margin-top: 20px;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background-color: #f9f9f9;
        }
        .question-preview {
            background: white;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #2c5aa0;
        }
        .format-guide {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .output-area {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Excel Question Import Tool</h1>
            <p>Upload Excel file to automatically convert questions to database format</p>
        </div>

        <div class="format-guide">
            <h3>Excel Format Requirements:</h3>
            <p><strong>Column A:</strong> Question Type (single/multiple/judge)</p>
            <p><strong>Column B:</strong> Subject (math/chinese/english/science)</p>
            <p><strong>Column C:</strong> Question Text</p>
            <p><strong>Column D:</strong> Option A</p>
            <p><strong>Column E:</strong> Option B</p>
            <p><strong>Column F:</strong> Option C</p>
            <p><strong>Column G:</strong> Option D</p>
            <p><strong>Column H:</strong> Correct Answer (e.g., "A" or "A,C" for multiple choice)</p>
            <p><strong>Column I:</strong> Explanation</p>
        </div>

        <div class="upload-area" id="uploadArea">
            <p>Click here or drag Excel file to upload</p>
            <p style="color: #666; font-size: 14px;">Supports .xlsx, .xls files</p>
            <input type="file" id="fileInput" class="file-input" accept=".xlsx,.xls" />
        </div>

        <div style="text-align: center;">
            <button class="btn" onclick="document.getElementById('fileInput').click()">Select Excel File</button>
            <button class="btn" onclick="generateDataFile()" id="generateBtn" style="display: none;">Generate data.js File</button>
            <button class="btn" onclick="copyToClipboard()" id="copyBtn" style="display: none;">Copy to Clipboard</button>
        </div>

        <div id="previewArea" class="preview-area" style="display: none;">
            <h3>Question Preview:</h3>
            <div id="questionList"></div>
        </div>

        <div id="outputArea" class="output-area" style="display: none;">
            <h3>Generated Code:</h3>
            <pre id="generatedCode"></pre>
        </div>
    </div>

    <script>
        let parsedQuestions = [];
        let nextQuestionId = 16; // Start from 16 to avoid conflicts

        // File upload handling
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');

        uploadArea.addEventListener('click', () => fileInput.click());
        uploadArea.addEventListener('dragover', handleDragOver);
        uploadArea.addEventListener('drop', handleDrop);
        fileInput.addEventListener('change', handleFileSelect);

        function handleDragOver(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                processFile(files[0]);
            }
        }

        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                processFile(file);
            }
        }

        function processFile(file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
                    
                    parseQuestions(jsonData);
                } catch (error) {
                    alert('Error reading file: ' + error.message);
                }
            };
            reader.readAsArrayBuffer(file);
        }

        function parseQuestions(data) {
            parsedQuestions = [];
            
            // Skip header row, start from row 1
            for (let i = 1; i < data.length; i++) {
                const row = data[i];
                if (!row || row.length < 8) continue; // Skip empty or incomplete rows
                
                const question = {
                    id: nextQuestionId++,
                    type: normalizeType(row[0]),
                    subject: normalizeSubject(row[1]),
                    question: row[2] || '',
                    options: [row[3], row[4], row[5], row[6]].filter(opt => opt),
                    correctAnswer: parseCorrectAnswer(row[7], row[0]),
                    explanation: row[8] || 'No explanation provided'
                };
                
                if (question.question && question.options.length > 0) {
                    parsedQuestions.push(question);
                }
            }
            
            displayPreview();
            document.getElementById('generateBtn').style.display = 'inline-block';
        }

        function normalizeType(type) {
            if (!type) return 'single';
            const t = type.toString().toLowerCase();
            if (t.includes('multiple') || t.includes('多选')) return 'multiple';
            if (t.includes('judge') || t.includes('判断')) return 'judge';
            return 'single';
        }

        function normalizeSubject(subject) {
            if (!subject) return 'math';
            const s = subject.toString().toLowerCase();
            if (s.includes('chinese') || s.includes('语文')) return 'chinese';
            if (s.includes('english') || s.includes('英语')) return 'english';
            if (s.includes('science') || s.includes('科学')) return 'science';
            return 'math';
        }

        function parseCorrectAnswer(answer, type) {
            if (!answer) return 0;
            
            const answerStr = answer.toString().toUpperCase();
            const typeNorm = normalizeType(type);
            
            if (typeNorm === 'multiple') {
                // Handle multiple answers like "A,C" or "AC"
                const answers = [];
                if (answerStr.includes(',')) {
                    answerStr.split(',').forEach(a => {
                        const index = a.trim().charCodeAt(0) - 65;
                        if (index >= 0 && index <= 3) answers.push(index);
                    });
                } else {
                    for (let char of answerStr) {
                        const index = char.charCodeAt(0) - 65;
                        if (index >= 0 && index <= 3) answers.push(index);
                    }
                }
                return answers.length > 0 ? answers : [0];
            } else {
                // Single choice or judge
                const index = answerStr.charCodeAt(0) - 65;
                return (index >= 0 && index <= 3) ? index : 0;
            }
        }

        function displayPreview() {
            const previewArea = document.getElementById('previewArea');
            const questionList = document.getElementById('questionList');
            
            questionList.innerHTML = '';
            
            parsedQuestions.slice(0, 5).forEach((q, index) => {
                const div = document.createElement('div');
                div.className = 'question-preview';
                div.innerHTML = `
                    <strong>Question ${q.id}:</strong> ${q.question}<br>
                    <strong>Type:</strong> ${q.type} | <strong>Subject:</strong> ${q.subject}<br>
                    <strong>Options:</strong> ${q.options.join(', ')}<br>
                    <strong>Answer:</strong> ${Array.isArray(q.correctAnswer) ? q.correctAnswer.map(i => String.fromCharCode(65 + i)).join(',') : String.fromCharCode(65 + q.correctAnswer)}
                `;
                questionList.appendChild(div);
            });
            
            if (parsedQuestions.length > 5) {
                const moreDiv = document.createElement('div');
                moreDiv.innerHTML = `<p><em>... and ${parsedQuestions.length - 5} more questions</em></p>`;
                questionList.appendChild(moreDiv);
            }
            
            previewArea.style.display = 'block';
        }

        function generateDataFile() {
            let code = `// Question database\nconst questionDatabase = [\n`;
            
            // Add existing questions comment
            code += `    // Existing questions (1-15) would be here\n\n`;
            
            // Add imported questions
            code += `    // Imported questions from Excel\n`;
            
            parsedQuestions.forEach((q, index) => {
                code += `    {\n`;
                code += `        id: ${q.id},\n`;
                code += `        type: '${q.type}',\n`;
                code += `        subject: '${q.subject}',\n`;
                code += `        question: '${q.question.replace(/'/g, "\\'")}',\n`;
                code += `        options: [${q.options.map(opt => `'${opt.replace(/'/g, "\\'")}'`).join(', ')}],\n`;
                code += `        correctAnswer: ${Array.isArray(q.correctAnswer) ? `[${q.correctAnswer.join(', ')}]` : q.correctAnswer},\n`;
                code += `        explanation: '${q.explanation.replace(/'/g, "\\'")}'`;
                code += `\n    }`;
                if (index < parsedQuestions.length - 1) code += ',';
                code += `\n\n`;
            });
            
            code += `];\n\n`;
            code += `// Export for use in other files\n`;
            code += `if (typeof module !== 'undefined' && module.exports) {\n`;
            code += `    module.exports = questionDatabase;\n`;
            code += `}`;
            
            document.getElementById('generatedCode').textContent = code;
            document.getElementById('outputArea').style.display = 'block';
            document.getElementById('copyBtn').style.display = 'inline-block';
        }

        function copyToClipboard() {
            const code = document.getElementById('generatedCode').textContent;
            navigator.clipboard.writeText(code).then(() => {
                alert('Code copied to clipboard! You can now paste it into your data.js file.');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = code;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('Code copied to clipboard!');
            });
        }

        // Remove dragover class when dragging leaves the area
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
    </script>
</body>
</html>